package com.haoxuer.discover.user.shiro.filter;

import com.google.gson.Gson;
import com.haoxuer.discover.rest.base.ResponseObject;

import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

public class RestAccessControlFilter extends AccessControlFilter {
  @Override
  protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
    Subject subject = getSubject(servletRequest, servletResponse);
    if (subject.isAuthenticated()) {
      return true;
    } else {
      if (isAjax(servletRequest)) {
        out(servletResponse);
      }
      return Boolean.FALSE;
    }
  }

  /**
   * 使用	response 输出JSON
   */
  public void out(ServletResponse response) {
    PrintWriter out = null;
    try {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/json");
      out = response.getWriter();
      Gson gson = new Gson();
      ResponseObject result = new ResponseObject();
      result.setMsg("你没有登陆");
      result.setCode(-100);
      out.println(gson.toJson(result));
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (null != out) {
        out.flush();
        out.close();
      }
    }
  }

  @Override
  protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
    saveRequestAndRedirectToLogin(servletRequest, servletResponse);
    return false;
  }

  /**
   * 是否是Ajax请求
   *
   * @param request
   * @return
   */
  public static boolean isAjax(ServletRequest request) {
    String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
    if ("XMLHttpRequest".equalsIgnoreCase(header)) {
      return Boolean.TRUE;
    }
    return Boolean.FALSE;
  }
}
